﻿using KWT.DRG_DIP.API.Infrastructure;
using KWT.DRG_DIP.Common;
using KWT.DRG_DIP.DB;
using KWT.DRG_DIP.DTO.Basic.SecretKey;
using KWT.DRG_DIP.PO.Basic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using OfficeOpenXml;

namespace KWT.DRG_DIP.API.Controllers.Basic
{
    /// <summary>
    /// 卡密
    /// </summary>
    [ApiExplorerSettings(GroupName = "basic")]
    public class SecretKeyController : BasicControllerBase
    {
        public EFContext ef { get; set; }

        /// <summary>
        /// 批量生成卡密
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]

        public IActionResult BatchCreate(InAdd dto)
        {
            if (CurrentUser.RoleID != "99")
            {
                return Fail("抱歉！您没有权限");
            }
            var key = new List<Sys_SecretKey>();
            string batch = _Tool.RandomString(10);
            for (int i = 0; i < dto.Count; i++)
            {
                key.Add(new Sys_SecretKey()
                {
                    KeyID = "SK" + snow_id.CreateId().ToString(),
                    Batch = batch,
                    Value = _Tool.RandomString(8),
                    Quota = dto.Quota,
                    Name = dto.Name,
                    Type = dto.Type,
                    Category = dto.Category,
                    Number = dto.Number,
                    AIQuota = dto.AIQuota,
                    AIType = dto.AIType,
                });
            }
            var _key = key.DistinctBy(x => x.Value);
            if (_key.Count() != key.Count)
            {
                return Fail("生成了重复卡密，请重试！"); ;
            }
            ef.AddRange(key);
            var a= ef.SaveChanges() > 0;
            return Output(a, "批量生成成功！", "批量生成有重复项,请重试！");
        }

        /// <summary>
        /// 分页列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PageList(DTO.Basic.SecretKey.InPageList dto)
        {
            if (CurrentUser.RoleID.Equals("2"))
            {
                dto.Batchs = new List<string> { "hd4eKJBXeZ", "UJU42B7ZfY", "fTcuZThjMC", "ZNi4jX2Eix" };
            }
            else
            {
                dto.Batchs = new List<string> { };
            }
            var q1 = ef.Set<Sys_User>().AsQueryable();
            var q2 = ef.Set<Sys_SecretKey>().AsQueryable();
            var q3 = ef.Set<Sys_Record>().AsQueryable();

            if (!string.IsNullOrEmpty(dto.UserID))
            {
                q2 = q2.Where(x => x.UserID == dto.UserID);
            }
            if (dto.Status >= 0)
            {
                q2 = q2.Where(x => x.Status == dto.Status);
            }
            if (!string.IsNullOrEmpty(dto.Batch))
            {
                q2 = q2.Where(x => x.Batch == dto.Batch);
            }
            if (!string.IsNullOrEmpty(dto.Name))
            {
                q2 = q2.Where(x => EF.Functions.Like(x.Name, $"%{dto.Name}%"));
            }
            if (!string.IsNullOrEmpty(dto.Value))
            {
                q2 = q2.Where(x => x.Value == dto.Value);
            }
            if (dto.Type >= -1)
            {
                q2 = q2.Where(x => x.Type == dto.Type);
            }
            if (dto.Create_date[0].HasValue && dto.Create_date[1].HasValue)
            {
                q2 = q2.Where(x => x.AddTime >= dto.Create_date[0] && x.AddTime < dto.Create_date[1]);
            }
            if (dto.Use_date[0].HasValue && dto.Use_date[1].HasValue)
            {
                q2 = q2.Where(x => x.UpdTime >= dto.Use_date[0] && x.UpdTime < dto.Use_date[1]);
            }
            if (dto.Batchs.Count > 0)
            {
                q2 = q2.Where(x => dto.Batchs.Contains(x.Batch));
            }
            var q = (from x in q2
                     join y in q1 on x.UserID equals y.UserID into xy
                     from _xy in xy.DefaultIfEmpty()
                     join z in q3 on x.KeyID equals z.KeyID into xz
                     from _xz in xz.DefaultIfEmpty()
                     where string.IsNullOrEmpty(dto.Phone) || _xy.Phone == dto.Phone
                     orderby x.AddTime descending
                     select new OutPageList()
                     {
                         KeyID = x.KeyID,
                         Batch = x.Batch,
                         Value = x.Value,
                         UserID = _xy == null ? "" : _xy.UserID,
                         Phone = _xy == null ? "" : _xy.Phone,
                         LoginName = _xy == null ? "" : _xy.LoginName,
                         RealName = _xy == null ? "" : _xy.RealName,
                         Status = x.Status,
                         Name = x.Name,
                         Quota = x.Quota,
                         Type = x.Type,
                         AddTime = x.AddTime,
                         UpdTime = x.UpdTime,
                         Number = x.Number,
                         AIQuota = x.AIQuota,
                         AIType = x.AIType,
                         Category = x.Category,
                         AccountID = _xz.AccountID
                     });
            int total = q.Count();
            var list = q.ToPageList(dto.PageNo, dto.PageSize);
            return PageList(list, total);
        }

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Export(DTO.Basic.SecretKey.InPageList dto)
        {
            if (CurrentUser.RoleID.Equals("2"))
            {
                dto.Batchs = new List<string> { "hd4eKJBXeZ", "UJU42B7ZfY", "fTcuZThjMC", "ZNi4jX2Eix" };
            }
            else
            {
                dto.Batchs = new List<string> { };
            }
            var q1 = ef.Set<Sys_User>().AsQueryable();
            var q2 = ef.Set<Sys_SecretKey>().AsQueryable();
            var q3 = ef.Set<Sys_Record>().AsQueryable();

            if (!string.IsNullOrEmpty(dto.UserID))
            {
                q2 = q2.Where(x => x.UserID == dto.UserID);
            }
            if (dto.Status >= 0)
            {
                q2 = q2.Where(x => x.Status == dto.Status);
            }
            if (!string.IsNullOrEmpty(dto.Batch))
            {
                q2 = q2.Where(x => x.Batch == dto.Batch);
            }
            if (!string.IsNullOrEmpty(dto.Name))
            {
                q2 = q2.Where(x => EF.Functions.Like(x.Name, $"%{dto.Name}%"));
            }
            if (!string.IsNullOrEmpty(dto.Value))
            {
                q2 = q2.Where(x => x.Value == dto.Value);
            }
            if (dto.Type >= -1)
            {
                q2 = q2.Where(x => x.Type == dto.Type);
            }
            if (dto.Create_date[0].HasValue && dto.Create_date[1].HasValue)
            {
                q2 = q2.Where(x => x.AddTime >= dto.Create_date[0] && x.AddTime < dto.Create_date[1]);
            }
            if (dto.Use_date[0].HasValue && dto.Use_date[1].HasValue)
            {
                q2 = q2.Where(x => x.UpdTime >= dto.Use_date[0] && x.UpdTime < dto.Use_date[1]);
            }
            if (dto.Batchs.Count > 0)
            {
                q2 = q2.Where(x => dto.Batchs.Contains(x.Batch));
            }
            var q = (from x in q2
                     join y in q1 on x.UserID equals y.UserID into xy
                     from _xy in xy.DefaultIfEmpty()
                     join z in q3 on x.KeyID equals z.KeyID into xz
                     from _xz in xz.DefaultIfEmpty()
                     where string.IsNullOrEmpty(dto.Phone) || _xy.Phone == dto.Phone
                     orderby x.AddTime descending
                     select new OutPageList()
                     {
                         KeyID = x.KeyID,
                         Batch = x.Batch,
                         Value = x.Value,
                         UserID = _xy == null ? "" : _xy.UserID,
                         Phone = _xy == null ? "" : _xy.Phone,
                         LoginName = _xy == null ? "" : _xy.LoginName,
                         RealName = _xy == null ? "" : _xy.RealName,
                         Status = x.Status,
                         Name = x.Name,
                         Quota = x.Quota,
                         Type = x.Type,
                         AddTime = x.AddTime,
                         UpdTime = x.UpdTime,
                         Number = x.Number,
                         AIQuota = x.AIQuota,
                         AIType = x.AIType,
                         Category = x.Category,
                         AccountID = _xz.AccountID
                     });
            int total = q.Count();
            var list = q.ToPageList(dto.PageNo, dto.PageSize);
            using var pck = new ExcelPackage();
            var sheet = pck.Workbook.Worksheets.Add("Sheet1");
            sheet.Cells["A1"].Value = "批次";
            sheet.Cells["B1"].Value = "卡密";
            sheet.Cells["C1"].Value = "额度";
            sheet.Cells["D1"].Value = "时效(-1:年，0：月，1：天)";
            sheet.Cells["E1"].Value = "名称";
            sheet.Cells["A2"].LoadFromCollection(list.Select(x => new { x.Batch, x.Value, x.Quota, x.Type, x.Name, }));
            sheet.Cells.Style.ShrinkToFit = true;
            var bytes = pck.GetAsByteArray();
            return Excel("卡密导出", bytes);
        }


        /// <summary>
        /// 作废
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public OutputResult Cancel(InCancel dto)
        {
            if (CurrentUser.RoleID != "99")
            {
                return Fail("抱歉！您没有权限");
            }
            var key = ef.Set<Sys_SecretKey>().SingleOrDefault(x => x.Value == dto.Code);
            var user = ef.Find<Sys_User>(key.UserID);
            if (user != null)
            {
                user.IsDel = true;
                ef.Attach(user);
            }
            key.Status = -2;
            ef.Attach(key);
            var flag = ef.SaveChanges() > 0;
            return Output(flag, "操作成功！", "操作失败！");
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public OutputResult Edit(InEdit dto)
        {
            if (CurrentUser.RoleID != "99")
            {
                return Fail("抱歉！您没有权限");
            }
            var key = ef.Find<Sys_SecretKey>(dto.KeyID);
            if (key.Status != 0)
            {
                return Fail("不是未使用状态不能修改！");
            }
            key.Category = dto.Category;
            key.Type = dto.Type;
            key.Name = dto.Name;
            key.Quota = dto.Quota;
            key.AIQuota = dto.AIQuota;
            key.AIType = dto.AIType;
            key.Number = dto.Number;
            ef.Attach(key);
            var flag = ef.SaveChanges() > 0;
            return Output(flag, "修改成功", "修改失败");
        }

        /// <summary>
        /// 详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public OutputResult Detail(string id)
        {
            var key = ef.Find<Sys_SecretKey>(id);
            return Output(key != null, "", "该项不存在", key);
        }
    }
}
